package com.parse.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	/**
	 * If the pathname is a folder,then create the folder.If the pathname is a
	 * file,create the parent folder and the file.
	 * 
	 * @param pathname
	 * @return
	 */
	public static boolean createFile(String pathname) {
		File file = new File(pathname);
		if (file.exists()) {
			return true;
		}

		if (pathname.lastIndexOf("\\") < pathname.lastIndexOf(".")
				|| pathname.lastIndexOf("/") < pathname.lastIndexOf(".")) {
			try {
				String[] array = StringUtils.split(pathname, "\\");
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < array.length; i++) {
					if (i != array.length - 1) {
						sb.append(array[i]);
						sb.append("\\");
					}
				}

				File tmp = new File(sb.toString());
				if (!tmp.exists()) {
					tmp.mkdirs();
				}

				sb.append(array[array.length - 1]);
				tmp = new File(sb.toString());
				if (!tmp.exists()) {
					tmp.createNewFile();
				}

				return file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		} else {
			return file.mkdirs();
		}

	}

	/**
	 * Get the all the folder and file name under this path.
	 * 
	 * @param pathname
	 * @return
	 */
	public static List<String> getAllFileNameUnderFolder(String pathname) {
		List<String> list = new ArrayList<>();
		File parent = new File(pathname);
		iteratorFolder(list, parent, null);
		return list;
	}

	/**
	 * Get the all the folder and file name under this path except the given path.
	 * @param pathname
	 * @param except
	 * @return
	 */
	public static List<String> getAllFileNameUnderFolderExcept(String pathname, String except) {
		List<String> list = new ArrayList<>();
		File parent = new File(pathname);
		iteratorFolder(list, parent, except);
		return list;
	}

	private static void iteratorFolder(List<String> list, File parent, String except) {
		if (!parent.exists()) {
			return;
		}

		if (except == null) {
			if (parent.isDirectory()) {
				File[] children = parent.listFiles();
				if (children == null || children.length == 0) {
					list.add(parent.getAbsolutePath());
				} else {
					for (File child : children) {
						iteratorFolder(list, child, null);
					}
				}

			} else {
				list.add(parent.getAbsolutePath());
			}
		} else {
			if (parent.isDirectory()) {
				File[] children = parent.listFiles();
				if (children == null || children.length == 0) {
					if (!parent.getAbsolutePath().endsWith(except)) {
						list.add(parent.getAbsolutePath());
					}
				} else {
					for (File child : children) {
						if (!child.getAbsolutePath().endsWith(except)) {
							iteratorFolder(list, child, except);
						}
					}
				}
			} else {
				if (!parent.getAbsolutePath().endsWith(except)) {
					list.add(parent.getAbsolutePath());
				}
			}
		}

	}
	
	
	public static boolean copyFile(String source, String target) {
		String full = target;
		int index = full.lastIndexOf("\\");
		if(index == -1){
			index = full.lastIndexOf("/");
		}
		String folder = full.substring(0,index);
		File fo = new File(folder);
		if(!fo.isDirectory()){
			fo.mkdirs();
		}
		
		File fileOld = new File(source);
		if (fileOld.exists()) {
			File fileTarget = new File(target);
			BufferedOutputStream stream = null;
			FileOutputStream fstream = null;
			InputStream in = null;
			try {
				in = new FileInputStream(fileOld); // 读入原文件
				byte[] bytes = toByteArray(in);
				fstream = new FileOutputStream(fileTarget);
				stream  = new BufferedOutputStream(fstream);
				stream.write(bytes);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("生成文件错误： source:"+source+ " target:"+target);
				return false;
			} finally {
				try {
					in.close();
					stream.close();
					fstream.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("关闭发生问题.");
					return false;
				}
			}
		}else{
			System.out.println("源文件不存在："+source);
		}
		return true;
	}

	/**
	 * These method copy from apache-io-util
	 * @param input
	 * @return
	 * @throws IOException
	 */
	// apache io util  start
	private static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		copy(input, output);
		return output.toByteArray();
	}

	private static int copy(InputStream input, OutputStream output) throws IOException {
		long count = copyLarge(input, output);
		if (count > 2147483647L) {
			return -1;
		}
		return (int) count;
	}

	private static long copyLarge(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[4096];
		long count = 0L;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}
	// apache io util  end

}
